package com.book.interceptor;

import com.alibaba.fastjson.JSON;
import com.book.common.Result;
import com.book.service.UserService;
import com.book.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行OPTIONS请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        
        // 获取token
        String token = request.getHeader("Authorization");
        
        if (!StringUtils.hasText(token)) {
            handleError(response, "Token不能为空");
            return false;
        }
        
        // 去掉Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        try {
            // 验证token
            String username = jwtUtil.getUsernameFromToken(token);
            if (!jwtUtil.validateToken(token, username)) {
                handleError(response, "Token无效");
                return false;
            }
            
            // 验证用户是否存在
            if (userService.getUserByUsername(username) == null) {
                handleError(response, "用户不存在");
                return false;
            }
            
            // 将用户信息存入request
            request.setAttribute("username", username);
            return true;
            
        } catch (Exception e) {
            handleError(response, "Token验证失败");
            return false;
        }
    }
    
    private void handleError(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Result<?> result = Result.error(401, message);
        response.getWriter().write(JSON.toJSONString(result));
    }
} 